import React, { Component } from 'react';
import { Card, Table, Form, Input, Button, Modal, message, Popconfirm } from 'antd';
import {
  queryAccountType,
  createAccountType,
  updateAccountType,
  deleteAccountType,
} from '@/services/account';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
@Form.create()
class AccountType extends Component {
  constructor(props) {
    super(props);
    this.state = {
      typeData: [],
      isFormVisible: false,
      currentOption: 'create',
      currentId: '',
      tableLoading: false,
    };
  }

  componentDidMount() {
    this.initialType();
  }

  // 初始获取类型

  initialType = async () => {
    this.setState({
      tableLoading: true,
    });
    const res = await queryAccountType();
    this.setState(
      {
        typeData: res.data.list,
      },
      () => {
        setTimeout(() => {
          this.setState({
            tableLoading: false,
          });
        }, 1000);
      },
    );
  };

  // 添加弹窗
  handleAdd = () => {
    this.setState({
      isFormVisible: true,
      currentOption: 'create',
    });
  };
  // 提交
  handleTypeSubmit = e => {
    e.preventDefault();
    console.log('12');
    const _this = this;
    this.props.form.validateFields((err, fieldsValue) => {
      if (!err) {
        console.log(fieldsValue);

        console.log(fieldsValue);
        this.submitForm(fieldsValue);

        this.props.form.resetFields();
        this.initialType();
      }
    });
  };
  // 请求创建账号的接口
  submitForm = async value => {
    const { currentOption } = this.state;
    if (currentOption == 'create') {
      const res = await createAccountType(value);
      if (res.code == 0) {
        message.success('添加成功');
      }
      this.initialType();
      setTimeout(() => {
        this.setState({
          isFormVisible: false,
        });
      }, 1000);
    } else {
      const _id = this.state.currentId;
      const values = { ...value, _id };
      console.log('values');
      console.log(values);
      const res = await updateAccountType(values);
      if (res.code == 0) {
        message.success('修改成功');
      }
      this.initialType();
      setTimeout(() => {
        this.setState({
          isFormVisible: false,
        });
      }, 1000);
    }
  };
  handleCancel = () => {
    this.setState({
      isFormVisible: false,
    });
    this.props.form.resetFields();
  };
  // 编辑按钮事件
  handleEditType = record => {
    console.log(record);

    this.props.form.setFieldsValue(
      {
        name: record.name,
        value: record.value,
      },
      () => {
        console.log('赋值');
        this.setState({
          isFormVisible: true,
          currentOption: 'update',
          currentId: record._id,
        });
      },
    );
  };
  // 删除按钮事件
  handleDelete = async record => {
    const id = record._id;
    const res = await deleteAccountType({ id });
    if (res.code == 0) {
      this.initialType();
      message.success('删除成功');
    } else {
      message.error('操作失败');
    }
  };
  handleAsync = () => {
    this.initialType();
  };
  render() {
    const columns = [
      { title: '名称', dataIndex: 'name', key: 'name' },
      { title: '值', dataIndex: 'value', key: 'value' },
      {
        title: '操作',
        key: 'action',
        render: record => {
          return (
            <div>
              <Button type="link" onClick={() => this.handleEditType(record)}>
                编辑
              </Button>
              <Popconfirm
                title="确定删除?"
                onConfirm={() => this.handleDelete(record)}
                onCancel={() => console.log('取消')}
                okText="是"
                cancelText="否"
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    const { typeData, isFormVisible, tableLoading } = this.state;
    return (
      <PageHeaderWrapper>
        <div>
          <Card>
            <div>
              <Button type="primary" onClick={this.handleAdd}>
                添加账户类型
              </Button>
              <Button onClick={this.handleAsync} style={{ float: 'right' }}>
                刷新
              </Button>
            </div>
            <Modal
              visible={isFormVisible}
              onOk={this.handleTypeSubmit}
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label="名称" style={{ marginTop: '20px' }}>
                  {getFieldDecorator('name', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input placeholder="请输入名称"></Input>)}
                </Form.Item>
                <Form.Item label="值">
                  {getFieldDecorator('value', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input placeholder="请输入类型值"></Input>)}
                </Form.Item>
              </Form>
            </Modal>
            <div>
              {' '}
              <Table
                dataSource={typeData}
                columns={columns}
                style={{ marginTop: '20px' }}
                loading={tableLoading}
              ></Table>
            </div>
          </Card>
        </div>
      </PageHeaderWrapper>
    );
  }
}
export default AccountType;
